package wechat

import (
	"io/ioutil"
	"os"
	"sync"

	jsoniter "github.com/json-iterator/go"
)

const expire int64 = 7000
const jsonpath = "static/json"
const publicjsonpath = jsonpath + "/public.json"
const miniappjsonpath = jsonpath + "/miniapp.json"

type Wx struct {
	config             WxConfig
	publicAccesstoken  accesstokenS
	miniappAccesstoken accesstokenS
	m                  sync.Mutex
}

// WxConfig wx设置
type WxConfig struct {
	Appid         string
	Appsecret     string
	MiniAppid     string
	MiniAppsecret string
	H5Appid       string
	H5Appsecret   string
	Mchid         string
	Mchkey        string
	MchidApp      string
	MchkeyApp     string
}

type accesstokenS struct {
	Cretetime   int64  `json:"create_time"`
	Accesstoken string `json:"access_token"`
}

func New(config WxConfig) *Wx {
	pat, err := readAccesstoken(publicjsonpath)
	if err != nil {
		panic(err)
	}
	mat, err := readAccesstoken(miniappjsonpath)
	if err != nil {
		panic(err)
	}
	return &Wx{
		config:             config,
		publicAccesstoken:  pat,
		miniappAccesstoken: mat,
	}
}

func readAccesstoken(filepath string) (at accesstokenS, err error) {
	pb, err := ioutil.ReadFile(filepath)
	if err != nil {
		return
	}
	err = jsoniter.Unmarshal(pb, &at)
	return
}

func exist(path string) bool {
	_, err := os.Stat(path)
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

func init() {
	_ = os.MkdirAll(jsonpath, 0777)
	if !exist(publicjsonpath) {
		f, _ := os.Create(publicjsonpath)
		defer f.Close()
		_, _ = f.WriteString("{}")
	}
	if !exist(miniappjsonpath) {
		f2, _ := os.Create(miniappjsonpath)
		defer f2.Close()
		_, _ = f2.WriteString("{}")
	}
}
